# 迷宫
import pygame
import sys
import random

# 初始化Pygame
pygame.init()

# 设置窗口大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置标题
pygame.display.set_caption("迷宫逃脱游戏")

# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)

# 迷宫参数
maze_width = 20
maze_height = 20
cell_size = 30
wall_chance = 0.25


# 生成迷宫
def generate_maze(width, height):
    maze = [[1] * width + [1] for _ in range(height)] + [[1] * (width + 1)]
    for y in range(height):
        for x in range(width):
            if random.random() < wall_chance:
                maze[y][x] = 1
            else:
                maze[y][x] = 0
    return maze


maze = generate_maze(maze_width, maze_height)

# 玩家角色
player = {'x': 1, 'y': 1}
exit_point = {'x': maze_width - 2, 'y': maze_height - 2}

# 游戏主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # 键盘控制
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT and maze[player['y']][player['x'] - 1] == 0:
                player['x'] -= 1
            elif event.key == pygame.K_RIGHT and maze[player['y']][player['x'] + 1] == 0:
                player['x'] += 1
            elif event.key == pygame.K_UP and maze[player['y'] - 1][player['x']] == 0:
                player['y'] -= 1
            elif event.key == pygame.K_DOWN and maze[player['y'] + 1][player['x']] == 0:
                player['y'] += 1

    # 判断是否到达出口
    if player['x'] == exit_point['x'] and player['y'] == exit_point['y']:
        print("恭喜你找到了出口！")
        running = False

    # 清屏
    screen.fill(black)

    # 绘制迷宫
    for y in range(len(maze)):
        for x in range(len(maze[y])):
            if maze[y][x] == 1:
                pygame.draw.rect(screen, white, (x * cell_size, y * cell_size, cell_size, cell_size))

    # 绘制玩家
    pygame.draw.rect(screen, green, (player['x'] * cell_size, player['y'] * cell_size, cell_size, cell_size))

    # 绘制出口
    pygame.draw.rect(screen, red, (exit_point['x'] * cell_size, exit_point['y'] * cell_size, cell_size, cell_size))

    # 更新屏幕显示
    pygame.display.flip()

# 清理并退出Pygame
pygame.quit()
sys.exit()